<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/myblog/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/myblog/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/myblog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/myblog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/myblog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/myblog/images/apple-touch-icon.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/myblog/images/favicon-32x32.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/myblog/images/favicon-16x16.png?v=5.1.4">


  <link rel="mask-icon" href="/myblog/images/safari-pinned-tab.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="java,stream,转载,">










<meta name="description" content="作者：Howie_Y   主页：www.jianshu.com/u/79638e5f0743  上一篇文章我讲解 Stream 流的基本原理，以及它的基本方法使用，本篇文章我们继续讲解流的其他操作  值得注意的是：学习 Stream 之前必须先学习 lambda 的相关知识。本文也假设读者已经掌握 lambda 的相关知识。 本篇文章主要内容：  一种特化形式的流——数值流 Optional 类">
<meta name="keywords" content="java,stream,转载">
<meta property="og:type" content="article">
<meta property="og:title" content="【转】简洁又快速地处理集合——java8 Stream（下）">
<meta property="og:url" content="https://github.com/lgsxiaosen/post/9e7dbf5a.html">
<meta property="og:site_name" content="Learning Notes">
<meta property="og:description" content="作者：Howie_Y   主页：www.jianshu.com/u/79638e5f0743  上一篇文章我讲解 Stream 流的基本原理，以及它的基本方法使用，本篇文章我们继续讲解流的其他操作  值得注意的是：学习 Stream 之前必须先学习 lambda 的相关知识。本文也假设读者已经掌握 lambda 的相关知识。 本篇文章主要内容：  一种特化形式的流——数值流 Optional 类">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-01-19T08:29:23.062Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【转】简洁又快速地处理集合——java8 Stream（下）">
<meta name="twitter:description" content="作者：Howie_Y   主页：www.jianshu.com/u/79638e5f0743  上一篇文章我讲解 Stream 流的基本原理，以及它的基本方法使用，本篇文章我们继续讲解流的其他操作  值得注意的是：学习 Stream 之前必须先学习 lambda 的相关知识。本文也假设读者已经掌握 lambda 的相关知识。 本篇文章主要内容：  一种特化形式的流——数值流 Optional 类">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/myblog/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://github.com/lgsxiaosen/post/9e7dbf5a.html">





<script>
    (function () {
        if ('') {
            if (prompt('请输入文章密码') !== '') {
                alert('密码错误！');
                if (history.length === 1) {
                    location.replace("https://lgsdaredevil.github.io/myblog"); // 这里替换成你的首页
                } else {
                    history.back();
                }
            }
        }
    })();
</script>
  <title>【转】简洁又快速地处理集合——java8 Stream（下） | Learning Notes</title>
  








</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/myblog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Learning Notes</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/myblog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/myblog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/myblog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/myblog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/myblog/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/myblog/404.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br>
            
            公益404
          </a>
        </li>
      
        
        <li class="menu-item menu-item-comments">
          <a href="/myblog/comments" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            留言板
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://github.com/lgsxiaosen/myblog/post/9e7dbf5a.html">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="小森">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/myblog/images/android-chrome-192x192.png">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Learning Notes">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">【转】简洁又快速地处理集合——java8 Stream（下）</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-08-19T10:26:04+08:00">
                2018-08-19
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/myblog/categories/技术文章/" itemprop="url" rel="index">
                    <span itemprop="name">技术文章</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o">本文总阅读量</i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <blockquote>
<p>作者：Howie_Y</p>
</blockquote>
<blockquote>
<p>主页：<a href="http://www.jianshu.com/u/79638e5f0743" target="_blank" rel="noopener">www.jianshu.com/u/79638e5f0743</a></p>
</blockquote>
<p>上一篇文章我讲解 Stream 流的基本原理，以及它的基本方法使用，本篇文章我们继续讲解流的其他操作 </p>
<p><em>值得注意的是：学习 Stream 之前必须先学习 lambda 的相关知识。本文也假设读者已经掌握 lambda 的相关知识。</em></p>
<p><strong>本篇文章主要内容：</strong></p>
<ol>
<li>一种特化形式的流——数值流</li>
<li>Optional 类</li>
<li>如何构建一个流</li>
<li>collect 方法</li>
<li>并行流相关问题</li>
</ol>
<p><strong>一. 数值流</strong></p>
<p>前面介绍的如</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> sum = list.stream().map(Person::getAge).reduce(<span class="number">0</span>, Integer::sum);</span><br></pre></td></tr></table></figure>
<p>计算元素总和的方法其中暗含了装箱成本，map(Person::getAge) 方法过后流变成了 Stream类型，而每个 Integer 都要拆箱成一个原始类型再进行 sum 方法求和，这样大大影响了效率。</p>
<p>针对这个问题 Java 8 有良心地引入了数值流 IntStream, DoubleStream, LongStream，这种流中的元素都是原始数据类型，分别是 int，double，long</p>
<p><strong>1. 流与数值流的转换</strong></p>
<p><strong>流转换为数值流</strong></p>
<ul>
<li>mapToInt(T -&gt; int) : return IntStream</li>
<li>mapToDouble(T -&gt; double) : return DoubleStream</li>
<li>mapToLong(T -&gt; long) : return LongStream</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">IntStream intStream = list.stream().mapToInt(Person::getAge);</span><br></pre></td></tr></table></figure>
<p>当然如果是下面这样便会出错 </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">LongStream longStream = list.stream().mapToInt(Person::getAge);</span><br></pre></td></tr></table></figure>
<p>因为 getAge 方法返回的是 int 类型（返回的如果是 Integer，一样可以转换为 IntStream）</p>
<p><strong>数值流转换为流</strong></p>
<p>很简单，就一个 boxed</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Stream&lt;Integer&gt; stream = intStream.boxed();</span><br></pre></td></tr></table></figure>
<p><strong>2. 数值流方法</strong></p>
<p>下面这些方法作用不用多说，看名字就知道：</p>
<ul>
<li>sum()</li>
<li>max()</li>
<li>min()</li>
<li>average() 等…</li>
</ul>
<p><strong>3. 数值范围</strong></p>
<p>IntStream 与 LongStream 拥有 range 和 rangeClosed 方法用于数值范围处理</p>
<ul>
<li>IntStream ： rangeClosed(int, int) / range(int, int)</li>
<li>LongStream ： rangeClosed(long, long) / range(long, long)</li>
</ul>
<p>这两个方法的区别在于一个是闭区间，一个是半开半闭区间：</p>
<ul>
<li>rangeClosed(1, 100) ：[1, 100]</li>
<li>range(1, 100) ：[1, 100)</li>
</ul>
<p>我们可以利用 IntStream.rangeClosed(1, 100) 生成 1 到 100 的数值流</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//求 1 到 10 的数值总和：</span></span><br><span class="line">IntStream intStream = IntStream.rangeClosed(<span class="number">1</span>, <span class="number">10</span>);</span><br><span class="line"><span class="keyword">int</span> sum = intStream.sum();</span><br></pre></td></tr></table></figure>
<p><strong>二. Optional 类</strong></p>
<p>NullPointerException 可以说是每一个 Java 程序员都非常讨厌看到的一个词，针对这个问题， Java 8 引入了一个新的容器类 Optional，可以代表一个值存在或不存在，这样就不用返回容易出问题的 null。之前文章的代码中就经常出现这个类，也是针对这个问题进行的改进。</p>
<p>Optional 类比较常用的几个方法有：</p>
<ul>
<li>isPresent() ：值存在时返回 true，反之 flase</li>
<li>get() ：返回当前值，若值不存在会抛出异常</li>
<li>orElse(T) ：值存在时返回该值，否则返回 T 的值</li>
</ul>
<p>Optional 类还有三个特化版本 OptionalInt，OptionalLong，OptionalDouble，刚刚讲到的数值流中的 max 方法返回的类型便是这个</p>
<p>Optional 类其中其实还有很多学问，讲解它说不定也要开一篇文章，这里先讲那么多，先知道基本怎么用就可以。</p>
<p><strong>三. 构建流</strong></p>
<p>之前我们得到一个流是通过一个原始数据源转换而来，其实我们还可以直接构建得到流。</p>
<p><strong>1. 值创建流</strong></p>
<p>Stream.of(T…) ： Stream.of(“aa”, “bb”) 生成流</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//生成一个字符串流</span></span><br><span class="line">Stream&lt;String&gt; stream = Stream.of(<span class="string">"aaa"</span>, <span class="string">"bbb"</span>, <span class="string">"ccc"</span>);</span><br></pre></td></tr></table></figure>
<p>Stream.empty() : 生成空流</p>
<p><strong>2. 数组创建流</strong></p>
<p>根据参数的数组类型创建对应的流：</p>
<ul>
<li>Arrays.stream(T[ ])</li>
<li>Arrays.stream(int[ ])</li>
<li>Arrays.stream(double[ ])</li>
<li>Arrays.stream(long[ ])</li>
</ul>
<p>值得注意的是，还可以规定只取数组的某部分，用到的是Arrays.stream(T[], int, int)</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//只取索引第 1 到第 2 位的：</span></span><br><span class="line"><span class="keyword">int</span>[] a = &#123;<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>&#125;;</span><br><span class="line">Arrays.stream(a, <span class="number">1</span>, <span class="number">3</span>).forEach(System.out :: println);</span><br><span class="line"><span class="comment">//打印 2 ，3</span></span><br></pre></td></tr></table></figure>
<p><strong>3. 文件生成流</strong> </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Stream&lt;String&gt; stream = Files.lines(Paths.get(<span class="string">"data.txt"</span>));</span><br></pre></td></tr></table></figure>
<p>每个元素是给定文件的其中一行</p>
<p><strong>4. 函数生成流</strong></p>
<p>两个方法：</p>
<ul>
<li>iterate ： 依次对每个新生成的值应用函数</li>
<li>generate ：接受一个函数，生成一个新的值</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">Stream.iterate(<span class="number">0</span>, n -&gt; n + <span class="number">2</span>)</span><br><span class="line"><span class="comment">//生成流，首元素为 0，之后依次加 2</span></span><br><span class="line">Stream.generate(Math :: random)</span><br><span class="line"><span class="comment">//生成流，为 0 到 1 的随机双精度数</span></span><br><span class="line">Stream.generate(() -&gt; <span class="number">1</span>)</span><br><span class="line"><span class="comment">//生成流，元素全为 1</span></span><br></pre></td></tr></table></figure>
<p><strong>四. collect 收集数据</strong></p>
<p>coollect 方法作为终端操作，接受的是一个 Collector 接口参数，能对数据进行一些收集归总操作</p>
<p><strong>1. 收集</strong></p>
<p>最常用的方法，把流中所有元素收集到一个 List, Set 或 Collection 中</p>
<ul>
<li>toList</li>
<li>toSet</li>
<li>toCollection</li>
<li>toMap</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">List newlist = list.stream.collect(toList());</span><br><span class="line"><span class="comment">//如果 Map 的 Key 重复了，可是会报错的哦</span></span><br><span class="line">Map&lt;Integer, Person&gt; map = list.stream().collect(toMap(Person::getAge, p -&gt; p));</span><br></pre></td></tr></table></figure>
<p><strong>2. 汇总</strong></p>
<p><strong>（1）counting</strong></p>
<p>用于计算总和：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">long</span> l = list.stream().collect(counting());</span><br></pre></td></tr></table></figure>
<p>没错，你应该想到了，下面这样也可以： </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">long</span> l = list.stream().count();</span><br></pre></td></tr></table></figure>
<p>推荐第二种</p>
<p><strong>（2）summingInt ，summingLong ，summingDouble</strong></p>
<p>summing，没错，也是计算总和，不过这里需要一个函数参数</p>
<p>计算 Person 年龄总和：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> sum = list.stream().collect(summingInt(Person::getAge));</span><br></pre></td></tr></table></figure>
<p>当然，这个可以也简化为： </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> sum = list.stream().mapToInt(Person::getAge).sum();</span><br></pre></td></tr></table></figure>
<p>除了上面两种，其实还可以： </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> sum = list.stream().map(Person::getAge).reduce(Interger::sum).get();</span><br></pre></td></tr></table></figure>
<p>推荐第二种</p>
<p>由此可见，函数式编程通常提供了多种方式来完成同一种操作</p>
<p><strong>（3）averagingInt，averagingLong，averagingDouble</strong></p>
<p>看名字就知道，求平均数</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Double average = list.stream().collect(averagingInt(Person::getAge));</span><br></pre></td></tr></table></figure>
<p>当然也可以这样写 </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">OptionalDouble average = list.stream().mapToInt(Person::getAge).average();</span><br></pre></td></tr></table></figure>
<p>不过要注意的是，这两种返回的值是不同类型的</p>
<p><strong>（4）summarizingInt，summarizingLong，summarizingDouble</strong></p>
<p>这三个方法比较特殊，比如 summarizingInt 会返回 IntSummaryStatistics 类型</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">IntSummaryStatistics l = list.stream().collect(summarizingInt(Person::getAge));</span><br></pre></td></tr></table></figure>
<p>IntSummaryStatistics 包含了计算出来的平均值，总数，总和，最值，可以通过下面这些方法获得相应的数据 </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">getAverage()                                         <span class="keyword">double</span></span><br><span class="line">getCount()                                           <span class="keyword">long</span></span><br><span class="line">getMax()										 <span class="keyword">int</span></span><br><span class="line">getMin()										 <span class="keyword">int</span></span><br><span class="line">getSum()										 <span class="keyword">long</span></span><br></pre></td></tr></table></figure>
<p><strong>3. 取最值</strong></p>
<p>maxBy，minBy 两个方法，需要一个 Comparator 接口作为参数</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Optional&lt;Person&gt; optional = list.stream().collect(maxBy(comparing(Person::getAge)));</span><br></pre></td></tr></table></figure>
<p>我们也可以直接使用 max 方法获得同样的结果</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Optional&lt;Person&gt; optional = list.stream().max(comparing(Person::getAge));</span><br></pre></td></tr></table></figure>
<p><strong>4. joining 连接字符串</strong></p>
<p>也是一个比较常用的方法，对流里面的字符串元素进行连接，其底层实现用的是专门用于字符串连接的 StringBuilder</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">String s = list.stream().map(Person::getName).collect(Collectors.joining());</span><br><span class="line"><span class="comment">//结果：jackmiketom</span></span><br><span class="line">String s = list.stream().map(Person::getName).collect(Collectors.joining(<span class="string">","</span>));</span><br><span class="line"><span class="comment">//结果：jack,mike,tom</span></span><br></pre></td></tr></table></figure>
<p>joining 还有一个比较特别的重载方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">String s = list.stream().map(Person::getName).collect(Collectors.joining(<span class="string">" and "</span>, <span class="string">"Today "</span>, <span class="string">" play games."</span>));</span><br><span class="line"><span class="comment">//结果：Today jack and mike and tom play games.</span></span><br></pre></td></tr></table></figure>
<p>即 Today 放开头，play games. 放结尾，and 在中间连接各个字符串</p>
<p><strong>5. groupingBy 分组</strong></p>
<p>groupingBy 用于将数据分组，最终返回一个 Map 类型</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Map&lt;Integer, List&lt;Person&gt;&gt; map = list.stream().collect(groupingBy(Person::getAge));</span><br></pre></td></tr></table></figure>
<p>例子中我们按照年龄 age 分组，每一个 Person 对象中年龄相同的归为一组</p>
<p>另外可以看出，Person::getAge 决定 Map 的键（Integer 类型），list 类型决定 Map 的值（List类型）</p>
<p><strong>多级分组</strong></p>
<p>groupingBy 可以接受一个第二参数实现多级分组：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Map&lt;Integer, Map&lt;T, List&lt;Person&gt;&gt;&gt; map = list.stream().collect(groupingBy(Person::getAge, groupingBy(...)));</span><br></pre></td></tr></table></figure>
<p>其中返回的 Map 键为 Integer 类型，值为 Map&lt;t, list</p>
<p><strong>按组收集数据</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Map&lt;Integer, Integer&gt; map = list.stream().collect(groupingBy(Person::getAge, summingInt(Person::getAge)));</span><br></pre></td></tr></table></figure>
<p>该例子中，我们通过年龄进行分组，然后 summingInt(Person::getAge)) 分别计算每一组的年龄总和（Integer），最终返回一个 Map</p>
<p>根据这个方法，我们可以知道，前面我们写的：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">groupingBy(Person::getAge)</span><br></pre></td></tr></table></figure>
<p>其实等同于：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">groupingBy(Person::getAge, toList())</span><br></pre></td></tr></table></figure>
<p><strong>6. partitioningBy 分区</strong></p>
<p>分区与分组的区别在于，分区是按照 true 和 false 来分的，因此partitioningBy 接受的参数的 lambda 也是 T -&gt; boolean</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//根据年龄是否小于等于20来分区</span></span><br><span class="line">Map&lt;Boolean, List&lt;Person&gt;&gt; map = list.stream()</span><br><span class="line">                                    .collect(partitioningBy(p -&gt; p.getAge() &lt;= <span class="number">20</span>));</span><br><span class="line"><span class="comment">//打印输出</span></span><br><span class="line">&#123;</span><br><span class="line">   <span class="keyword">false</span>=[Person&#123;name=<span class="string">'mike'</span>, age=<span class="number">25</span>&#125;, Person&#123;name=<span class="string">'tom'</span>, age=<span class="number">30</span>&#125;], </span><br><span class="line">   <span class="keyword">true</span>=[Person&#123;name=<span class="string">'jack'</span>, age=<span class="number">20</span>&#125;]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>同样地 partitioningBy 也可以添加一个收集器作为第二参数，进行类似 groupBy 的多重分区等等操作。</p>
<p><strong>五. 并行</strong></p>
<p>我们通过 list.stream() 将 List 类型转换为流类型，我们还可以通过 list.parallelStream() 转换为并行流。因此你通常可以使用 parallelStream 来代替 stream 方法</p>
<p>并行流就是把内容分成多个数据块，使用不同的线程分别处理每个数据块的流。这也是流的一大特点，要知道，在 Java 7 之前，并行处理数据集合是非常麻烦的，你得自己去将数据分割开，自己去分配线程，必要时还要确保同步避免竞争。</p>
<p>Stream 让程序员能够比较轻易地实现对数据集合的并行处理，但要注意的是，不是所有情况的适合，有些时候并行甚至比顺序进行效率更低，而有时候因为线程安全问题，还可能导致数据的处理错误，这些我会在下一篇文章中讲解。</p>
<p>比方说下面这个例子</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> i = Stream.iterate(<span class="number">1</span>, a -&gt; a + <span class="number">1</span>).limit(<span class="number">100</span>).parallel().reduce(<span class="number">0</span>, Integer::sum);</span><br></pre></td></tr></table></figure>
<p>我们通过这样一行代码来计算 1 到 100 的所有数的和，我们使用了 parallel 来实现并行。</p>
<p>但实际上是，这样的计算，效率是非常低的，比不使用并行还低！一方面是因为装箱问题，这个前面也提到过，就不再赘述，还有一方面就是 iterate 方法很难把这些数分成多个独立块来并行执行，因此无形之中降低了效率。</p>
<p><strong>流的可分解性</strong></p>
<p>这就说到流的可分解性问题了，使用并行的时候，我们要注意流背后的数据结构是否易于分解。比如众所周知的 ArrayList 和 LinkedList，明显前者在分解方面占优。</p>
<p><strong>我们来看看一些数据源的可分解性情况</strong></p>
<p>数据源可分解性ArrayList极佳LinkedList差IntStream.range极佳Stream.iterate差HashSet好TreeSet好顺序性。</p>
<p>除了可分解性，和刚刚提到的装箱问题，还有一点值得注意的是一些操作本身在并行流上的性能就比顺序流要差，比如：limit，findFirst，因为这两个方法会考虑元素的顺序性，而并行本身就是违背顺序性的，也是因为如此 findAny 一般比 findFirst 的效率要高。</p>
<p><strong>六. 效率</strong></p>
<p>最后再来谈谈效率问题，很多人可能听说过有关 Stream 效率低下的问题。其实，对于一些简单的操作，比如单纯的遍历，查找最值等等，Stream 的性能的确会低于传统的循环或者迭代器实现，甚至会低很多。</p>
<p>但是对于复杂的操作，比如一些复杂的对象归约，Stream 的性能是可以和手动实现的性能匹敌的，在某些情况下使用并行流，效率可能还远超手动实现。好钢用在刀刃上，在适合的场景下使用，才能发挥其最大的用处。</p>
<p>函数式接口的出现主要是为了提高编码开发效率以及增强代码可读性；与此同时，在实际的开发中，并非总是要求非常高的性能，因此 Stream 与 lambda 的出现意义还是非常大的。</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>如果觉得我的文章对您有用，请随意打赏。您的支持将鼓励我继续创作!</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="https://raw.githubusercontent.com/lgsdaredevil/newblog/master/css/images/wechatlike.jpg" alt="小森 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="https://raw.githubusercontent.com/lgsdaredevil/newblog/master/css/images/alipay.png" alt="小森 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/myblog/tags/java/" rel="tag"><i class="fa fa-tag"></i> java</a>
          
            <a href="/myblog/tags/stream/" rel="tag"><i class="fa fa-tag"></i> stream</a>
          
            <a href="/myblog/tags/转载/" rel="tag"><i class="fa fa-tag"></i> 转载</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/myblog/post/26c1d83f.html" rel="next" title="【转】简洁又快速地处理集合——java8 Stream（上）">
                <i class="fa fa-chevron-left"></i> 【转】简洁又快速地处理集合——java8 Stream（上）
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/myblog/post/17750952.html" rel="prev" title="计算机网络协议">
                计算机网络协议 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      
        <div onclick="showGitment()" id="gitment-display-button">显示 Gitment 评论</div>
        <div id="gitment-container" style="display:none"></div>
      
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/myblog/images/android-chrome-192x192.png" alt="小森">
            
              <p class="site-author-name" itemprop="name">小森</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/myblog/archives/">
              
                  <span class="site-state-item-count">41</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/myblog/categories/index.html">
                  <span class="site-state-item-count">3</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/myblog/tags/index.html">
                  <span class="site-state-item-count">24</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/lgsxiaosen/myblog" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

<div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">小森</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>




<!-- <div class="powered-by">
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv">
  本站访客数:<span id="busuanzi_value_site_uv"></span>
</span>
</div> -->

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user">本站访客数</i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye">本站总访问量</i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  









  



  
  
    <script type="text/javascript" src="/myblog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/myblog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/myblog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/myblog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/myblog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/myblog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/myblog/lib/canvas-nest/canvas-nest.min.js"></script>
  

  
  
    <script id="ribbon" type="text/javascript" size="300" alpha="0.6" zindex="-1" src="/myblog/lib/canvas-ribbon/canvas-ribbon.js"></script>
  


  


  <script type="text/javascript" src="/myblog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/myblog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/myblog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/myblog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/myblog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/myblog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/myblog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  







<!-- LOCAL: You can save these files to your site and update links -->
    
        
        <link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css">
        <!-- <script src="https://imsun.github.io/gitment/dist/gitment.browser.js"></script> -->
        <script src="https://www.wenjunjiang.win/js/gitment.js"></script>
    
<!-- END LOCAL -->

    
      <style>
        a.gitment-editor-footer-tip { display: none; }
        .gitment-container.gitment-footer-container { display: none; }
      </style>
    

    
      <script type="text/javascript">
      function renderGitment(){
        var gitment = new Gitment({
            id: window.location.pathname, 
            owner: 'lgsxiaosen',
            repo: 'myblog',
            
            oauth: {
            
            
                client_secret: '876f37e17b73ba2870db494ed0b23e3194068dc9',
            
                client_id: '63acdc65d11c172104c4'
            }});
        gitment.render('gitment-container');
      }

      
      function showGitment(){
        document.getElementById("gitment-display-button").style.display = "none";
        document.getElementById("gitment-container").style.display = "block";
        renderGitment();
      }
      
      </script>
    







  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/myblog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

<script src="/myblog/live2dw/lib/L2Dwidget.min.js?0c58a1486de42ac6cc1c59c7d98ae887"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","model":{"jsonPath":"/myblog/live2dw/assets/wanko.model.json"},"display":{"position":"right","width":80,"height":200},"mobile":{"show":true},"log":false,"tagMode":false});</script></body>
</html>
